package org.jeecg.modules.bobo.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.bobo.common.util.Result;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @program: jeecg-boot-parent
 * @description:
 * @author: 三千霜
 * @create: 2020-07-26 10:14
 */
@RestControllerAdvice
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class BoboExceptionHandler {
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BoboException.class)
    @ResponseBody
    public Result<?> handleRRException(BoboException e){
        log.error(e.getMessage(), e);
        return Result.error(e.getCode(),e.getMessage());
    }
    /**
     * 处理验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<?> handleRRException(MethodArgumentNotValidException e){
        // 获取异常信息
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                return Result.error(500,fieldError.getDefaultMessage());
            }
        }
        return Result.error(500,e.getMessage());
    }
}
